package org.ruanjj.multithread;

import java.util.concurrent.locks.ReentrantLock;

public class Demo {
    public static void main(String[] args) {
        ReentrantLockDemo demo = new ReentrantLockDemo();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                demo.A();
            }
        },"AA");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                demo.B();
            }
        },"BB");

        t1.start();
        t2.start();
    }
}


//测试可重入锁的特性
class ReentrantLockDemo{
    private int ticket = 0;
    ReentrantLock lock1 = new ReentrantLock();
    ReentrantLock lock2 = new ReentrantLock();
    public void A() {
        lock1.lock();
        int i = 0;
        while(i < 30){
            i++;
            if(ticket > 0){
                System.out.println(Thread.currentThread().getName()+":"+ticket);
                ticket--;
            }else{
                B();
            }
        }
        lock1.unlock();
    }

    public void B(){
        lock2.lock();
        int i = 0;
        while(i < 30) {
            i++;
            System.out.println(Thread.currentThread().getName() + ":" + ticket);
            ticket++;
        }
        lock2.unlock();
    }
}
